package com.lsyw.intergrate.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.common.util.DateUtil;
import com.lsyw.intergrate.entity.*;
import com.lsyw.intergrate.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

//@Component
public class MyTask {

    @Autowired
    private JcMassifFactorValueLogService jcMassifFactorValueLogService;
    @Autowired
    private JcMassifFactorValueService jcMassifFactorValueService;

    @Autowired
    private MassifPlanService massifPlanService;
    @Autowired
    private MassifPlanAlarmService massifPlanAlarmService;
    @Autowired
    private MassifService massifService;

    @Autowired
    private MesPointDataService mesPointDataService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MesDeviceService mesDeviceService;
    @Autowired
    private MesPointService mesPointService;

    @Scheduled(cron = "0 0/2 * * * ? ")
    @Async("taskExecutor")
    public void task2() {
        final LambdaQueryWrapper<JcMassifFactorValue> lambda1 = new QueryWrapper<JcMassifFactorValue>().lambda();
        lambda1.eq(JcMassifFactorValue::getDelFlag,0);
        lambda1.isNull(JcMassifFactorValue::getValue);
        lambda1.orderByAsc(JcMassifFactorValue::getGmtCreate);
        List<JcMassifFactorValue> list=jcMassifFactorValueService.list(lambda1);
        list.forEach(e->{
            JSONObject valueJson = JSON.parseObject(e.getFactorValue());
            JcMassifFactorValueLog jcMassifFactorValueLog=jcMassifFactorValueLogService.getById(e.getJcMassifFactorValueLog());
            if (jcMassifFactorValueLog.getCn().equals("2011")){
                if (valueJson.get("rtd")!=null){
                    e.setValue(Double.valueOf(valueJson.get("rtd").toString()));
                }
                if (valueJson.get("flag")!=null){

                    if (valueJson.get("flag").toString().contains("N")){
                        jcMassifFactorValueLog.setDeviceStatus(1);
                    }else{
                        jcMassifFactorValueLog.setDeviceStatus(2);
                    }
                    jcMassifFactorValueLogService.updateById(jcMassifFactorValueLog);
                }
            }else{
                if (valueJson.get("avg")!=null){
                    e.setValue(Double.valueOf(valueJson.get("avg").toString()));
                }
                if (valueJson.get("max")!=null){
                    e.setMaxValue(Double.valueOf(valueJson.get("max").toString()));
                }
                if (valueJson.get("flag")!=null){
                    if (valueJson.get("flag").toString().contains("N")){
                        jcMassifFactorValueLog.setDeviceStatus(1);
                    }else{
                        jcMassifFactorValueLog.setDeviceStatus(2);
                    }
                    jcMassifFactorValueLogService.updateById(jcMassifFactorValueLog);
                }
            }
            jcMassifFactorValueService.updateById(e);

        });
    }
    @Scheduled(cron = "0 0 0 * * ? ")
    public void task1() {
        List<MassifPlan> list1=massifService.getAllAlarm();
        list1.forEach(e->{
            Massif massif = massifService.getById(e.getMassifId());
            MassifPlanAlarm massifPlanAlarm=new MassifPlanAlarm();
            massifPlanAlarm.setDate(new Date());
            massifPlanAlarm.setStatus(2);
            massifPlanAlarm.setDelFlag(0);
            massifPlanAlarm.setGmtCreate(new Date());
            massifPlanAlarm.setMassifPlanId(e.getId());
            String content =massif.getName()+"计划"+ DateUtil.format(e.getDate()) +"完成的土壤修复"+e.getSoilPercent()+"% "+massif.getTrxfzfl() * e.getSoilPercent() / 100+"m³，地表水修复"+e.getWaterPercent()+"% "+massif.getDxsxfl() * e.getWaterPercent() / 100+"m³未修复完成，请注意该计划落实情况";

            massifPlanAlarm.setContent(content);
            massifPlanAlarmService.save(massifPlanAlarm);
        });
        List<MassifPlan> list2=massifService.getWaterAlarm();
        list2.forEach(e->{
            Massif massif = massifService.getById(e.getMassifId());
            MassifPlanAlarm massifPlanAlarm=new MassifPlanAlarm();
            massifPlanAlarm.setDate(new Date());
            massifPlanAlarm.setStatus(2);
            massifPlanAlarm.setDelFlag(0);
            massifPlanAlarm.setGmtCreate(new Date());
            massifPlanAlarm.setMassifPlanId(e.getId());
            String content =massif.getName()+"计划"+ DateUtil.format(e.getDate()) +"完成的地表水修复"+e.getWaterPercent()+"% "+massif.getDxsxfl() * e.getWaterPercent() / 100+"m³未修复完成，请注意该计划落实情况";

            massifPlanAlarm.setContent(content);
            massifPlanAlarmService.save(massifPlanAlarm);
        });
        List<MassifPlan> list3=massifService.getSoilAlarm();
        list3.forEach(e->{
            Massif massif = massifService.getById(e.getMassifId());
            MassifPlanAlarm massifPlanAlarm=new MassifPlanAlarm();
            massifPlanAlarm.setDate(new Date());
            massifPlanAlarm.setStatus(2);
            massifPlanAlarm.setDelFlag(0);
            massifPlanAlarm.setGmtCreate(new Date());
            massifPlanAlarm.setMassifPlanId(e.getId());
            String content =massif.getName()+"计划"+ DateUtil.format(e.getDate()) +"完成的土壤修复"+e.getSoilPercent()+"% "+massif.getTrxfzfl() * e.getSoilPercent() / 100+"m³未修复完成，请注意该计划落实情况";

            massifPlanAlarm.setContent(content);
            massifPlanAlarmService.save(massifPlanAlarm);
        });
    }
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void task3() {
        final LambdaQueryWrapper<MesDevice> lambda = new QueryWrapper<MesDevice>().lambda();
        lambda.eq(MesDevice::getDelFlag, 0);
        List<MesDevice> list = mesDeviceService.list(lambda);
        list.forEach(e -> {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("GRM", "54656790108");
            formData.add("PASS", "2024ddbs");
            formData.add("XINFO", "1");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

            String url = "http://www.yunplc.com:7080/exlog";
            // 假设服务器返回String表示操作结果
            String response = restTemplate.postForObject(url, requestEntity, String.class);
            if ((!response.contains("ERROR")) && response.contains("OK")) {
                String[] array = response.split("\r\n");
                String sid = array[2] + "&OP=R";
                String ip = array[1].substring(5);
                System.out.println(sid);
                final LambdaQueryWrapper<MesPoint> lambdaPoint = new QueryWrapper<MesPoint>().lambda();
                lambdaPoint.eq(MesPoint::getDelFlag, 0);

                List<MesPoint> pointList = mesPointService.list(lambdaPoint);
                final String[] param = {pointList.size() + "\r\n"};
                pointList.forEach(k -> {
                    param[0] += k.getName() + "\r\n";
                });
                param[0] = param[0].substring(0, param[0].length() - 2);
                System.out.println(param[0]);
                String url2 = "http://" + ip + "/exdata?" + sid;


                Date date =new Date();
                Long cn = date.getTime();
                String request = HttpRequest.post(url2)
                        .header("Content-Type", "application/text")
                        .body(param[0])
                        .execute().body();
                System.out.println(request);
                if ((!request.contains("ERROR")) && request.contains("OK")) {
                    String[] array2 = request.split("\r\n");
                    if (array2[0].equals("OK")) {
                        for (int i = 0; i < pointList.size(); i++) {
                            MesPointData mesPointData = new MesPointData();
                            mesPointData.setPointName(pointList.get(i).getName());
                            mesPointData.setMassifId(e.getMassifId());
                            mesPointData.setDeviceId(e.getId());
                            mesPointData.setCn(cn);
                            if (!array2[i + 2].contains("#")) {
                                mesPointData.setValue(Double.valueOf(array2[i + 2]));
                            }else{
                                mesPointData.setValue(0.0);
                            }
                            mesPointData.setDate(date);
                            mesPointData.setDelFlag(0);
                            mesPointDataService.save(mesPointData);
                        }
                    } else {
                        e.setStatus(2);
                        mesDeviceService.updateById(e);
                    }
                } else {
                    e.setStatus(2);
                    mesDeviceService.updateById(e);
                }

            } else {
                e.setStatus(2);
                mesDeviceService.updateById(e);
            }
        });

    }

}
